// pages/home/home.ts
const app = getApp<IAppOption>()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sysData:{},
    userInfo:{},
    barns:[],
    devices:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    var me = this;
    this.setData({
      sysData:app.globalData.sysData ,
      userInfo:app.globalData.userInfo
    },()=>{
      me.refresh();
    })
  },
  refresh() { 
    var me = this;
    try {
      var ps = {
        grainId : me.data.userInfo.grainId
      };
      app.api.callApi('custom/getBarnDevices' , ps).then(res=>{
        //console.log(res)
        res[1].forEach(d=>{
          d.info = {};
        })
        me.setData({
          barns:res[0],
          devices:res[1]
        },()=>{
          wx.showLoading({
            title: '加载中',
          })
          me.refreshDeviceInfos().then(_=>{
            wx.hideLoading();//console.log(me.data.devices)
          })
        })
      })
    } catch (error) {
      console.log(error);
    }    
  },
  refreshDeviceInfos(){
    var me = this;
    return new Promise((success , faild)=>{
      try {
        var ind =0;
        var devices = me.data.devices;
        var loadItem = ()=>{
          if( ind< devices.length ){
            var dev = devices[ind];
            app.api.getDeviceInfo(dev.snCode).then(info=>{
              dev.info = info;
              ind++;
              loadItem();
            })
          }
          else{
            me.setData({
              devices:devices
            }, ()=>{
              success();
            });
          }
        }
        loadItem();
      } catch (error) {
        console.log(error);
        success();
      }
    })
  },
  showDeviceDetail(en) { 
    var me = this;
    try { 
      var sncode = en.currentTarget.dataset.sncode;
      wx.navigateTo({
        url:"../device/device?snCode="+ sncode
      })
    } catch (error) {
      console.log(error);
    }    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.refresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})